package com.mediacloud.app.newsmodule.fragment.recommend;

import android.graphics.Color;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;

import androidx.annotation.NonNull;

import com.eventTrack.TXExposureEvnet;
import com.eventTrack.TXReportManager;
import com.google.gson.Gson;
import com.mediacloud.app.model.news.CMSFieldStyle;
import com.mediacloud.app.model.news.kt.TypeX;
import com.mediacloud.app.newsmodule.fragment.video.vod.PlayClickListener;
import com.mediacloud.app.newsmodule.fragment.video.vod.VideoListPlayerUtil;
import com.mediacloud.app.newsmodule.utils.ViewVisiblePercentToolKt;
import com.mediacloud.app.reslib.enums.XKey;
import com.mediacloud.app.user.model.UserInfo;
import com.mediacloud.app.model.component.ComponentItem;
import com.mediacloud.app.model.fragment.BaseFragment;
import com.mediacloud.app.model.interfaces.DataInvokeCallBack;
import com.mediacloud.app.model.news.ArticleItem;
import com.mediacloud.app.model.news.ArticleListData;
import com.mediacloud.app.model.news.CatalogItem;
import com.mediacloud.app.newsmodule.R;
import com.mediacloud.app.newsmodule.adaptor.NewsListItemStyleAdaptor;
import com.mediacloud.app.newsmodule.fragment.imagetext.RelatedType;
import com.mediacloud.app.newsmodule.utils.ComponentRelativeInvoker;
import com.mediacloud.app.newsmodule.utils.NewsItemClickUtils;
import com.mediacloud.app.view.XSmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadMoreListener;
import com.tencent.mmkv.MMKV;
import com.utils.SystemServiceManager;

/**
 * Created by yoake on 2017/9/27.
 */

public class RelatedListFragment extends BaseFragment implements AdapterView.OnItemClickListener, PlayClickListener, OnRefreshLoadMoreListener {
    private ListView mXRListView;
    private XSmartRefreshLayout fresh;
    private View mLoadingView;
    private View mEmptyContent;
    private NewsListItemStyleAdaptor articlesAdapter = null;
    private RelateArticledDataCallBack relateArticledDataCallBack;
    private ComponentRelativeInvoker componentRelativeInvoker;
    private int page = 1;
    private int perPage = 20;
    private String componentId;
    private String article_id;
    private int type;
    ComponentItem componentItem;
    String tipoff_catalogid = "";
    private VideoListPlayerUtil mVideoListPlayerUtil;
    private CatalogItem cat;


    private TXExposureEvnet txExposureEvnet = new TXExposureEvnet();

    @Override
    public int getLayoutResID() {
        return R.layout.aappfactory_fragment_related;
    }

    int visiblePosition = 0;
    int firstPosition = 0;
    public int curPosition = -1;
    int mNetType;
    int lastVisibleItemPosition = 0;
    private boolean checkNetType() {
        try {
            NetworkInfo networkInfo = SystemServiceManager.getConnectivityManager(getContext()).getActiveNetworkInfo();
            if (networkInfo != null && networkInfo.isAvailable()) {
                mNetType = networkInfo.getType();
                return true;
            }
            return false;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    @Override
    public void initView() {
        componentItem = getFragmentArguments().getParcelable("data");
        componentId = getFragmentArguments().getString("componentId");
        article_id = getFragmentArguments().getString("article_id");
        tipoff_catalogid = getFragmentArguments().getString("tipoff_catalogid");
        type = getFragmentArguments().getInt("type");
        fresh = findViewById(R.id.freshLayout);
        mXRListView = findViewById(R.id.listView);
        fresh.setEnableLoadMore(true);
        fresh.setEnableRefresh(true);
        fresh.setOnRefreshLoadMoreListener(this);
        mLoadingView = findViewById(R.id.mLoadingView);
        mEmptyContent = findViewById(R.id.mEmptyContent);
        cat = new CatalogItem();
        articlesAdapter = new NewsListItemStyleAdaptor(getContext(), cat, this);
        articlesAdapter.listView = mXRListView;
        mXRListView.setAdapter(articlesAdapter);

        txExposureEvnet.initExposureEventForListView(mXRListView,XKey.RELATED_EXPOSURE_EVENT);

        mXRListView.setOnItemClickListener(this);
        mXRListView.setOnScrollListener(new AbsListView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(AbsListView view, int scrollState) {
                try {
                    //滑动停止后，
                    if (scrollState == ListView.OVER_SCROLL_ALWAYS) {
//                        if (FloatButtonGroup.animatorFlag){
//                            if (translationX != null) {
//                                translationX.cancel();
//                            }
//                            if (translationX2 != null) {
//                                translationX2.start();
//                            }
//                        }

                        onScrollStateChangedX();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
                visiblePosition = visibleItemCount;
                firstPosition = firstVisibleItem;
            }
        });
        getRelateNewsList();
    }

    private void onScrollStateChangedX(){
        if (articlesAdapter==null){
            return;
        }
        boolean isAutoPlay = MMKV.defaultMMKV().decodeBool(XKey.AUTO_PLAY, false);
        if (!isAutoPlay) {
//                            Log.e("auto", "isAutoPlay: " + !isAutoPlay);
            return;
        }

        int yPs = 0;//有地址选择的时候出现问题，加一个修正值
        if (cat != null && cat.getLbsItem() != null) {
            yPs = 1;
        }
        lastVisibleItemPosition = firstPosition == 0 ? 0 : firstPosition;
        //是否自动播放

        //是否wifi
        if (checkNetType()) {
            if (mNetType != ConnectivityManager.TYPE_WIFI) {
                Log.e("auto", "not wifi");
                return;
            }
        }
        View itemView = null;
        ArticleItem mArticleItem = null;
        for (int i = 0; i < visiblePosition; i++) {
            View tempItemView = mXRListView.getChildAt(i);
            if (tempItemView!=null&&(tempItemView.getTop()>=0&&
                    ViewVisiblePercentToolKt.isFloatEquals(ViewVisiblePercentToolKt.getViewVisiblePercent(tempItemView), 1f))){
                //处理越界崩溃
                int tempPosition = firstPosition + i  - yPs;
                if (tempPosition>=0&&tempPosition<articlesAdapter.getListContentData().size()) {
                    Log.e("auto", "tempItemView--top:" + tempItemView.getTop() + "----bottom:" + tempItemView.getBottom() +
                            "---viewHeight:" + tempItemView.getHeight() + "---firstPosition:" + firstPosition +"----visiblePosition:"+visiblePosition+
                            "---tempPosition:" + tempPosition + "---title:" + ((ArticleItem) articlesAdapter.getListContentData().get(tempPosition)).getTitle());
                }
                if (curPosition == tempPosition&&tempPosition!=-1) {
                    return;
                }
                if ((tempPosition < 0) || (tempPosition >= articlesAdapter.getListContentData().size())) {
                    Log.e("auto", "over size ");
                    continue;
                }
                ArticleItem mTempArticleItem = (ArticleItem) articlesAdapter.getListContentData().get(tempPosition);

                if (mTempArticleItem.getType() == TypeX.NEWS.VIDEO) {
                    if (mTempArticleItem.getCmsCustomStyle() != null && mTempArticleItem.getCmsCustomStyle().getType() != CMSFieldStyle.None) {
                        if (mTempArticleItem.getCmsCustomStyle().getType() == CMSFieldStyle.BigImage16_9) {
                            curPosition = tempPosition;
                            mArticleItem = mTempArticleItem;
                            Log.e("auto", "curPosition: " + curPosition);
                            itemView = tempItemView;
                            break;
                        }

                    }
                } else {
                    Log.e("auto", "not video");
                }
            }
        }
        if (mArticleItem == null || TextUtils.isEmpty(mArticleItem.getVideo()) || mArticleItem.getVideo().equals("{}")) {
            Log.e("auto", "not have video path");
            return;
        }
        if (mArticleItem.getCmsCustomStyle() != null &&
                mArticleItem.getCmsCustomStyle().getType() != CMSFieldStyle.None) {
            if (mArticleItem.getCmsCustomStyle().getType() == CMSFieldStyle.BigImage16_9) {
                View videoLayout = itemView.findViewById(R.id.bigImgAndSpiderStyle);
                if (videoLayout != null) {
                    View itemIcon = videoLayout.findViewById(R.id.itemIcon);
                    itemIcon.performClick();
                }
            }

        }
    }


    @Override
    public void onResume() {
        super.onResume();

        curPosition = -1;
    }
   boolean needSend=false;
    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        curPosition = -1;
        if (txExposureEvnet != null) {
            txExposureEvnet.setUserVisibleHint(isVisibleToUser);
        }
    }

    @Override
    public void onPause() {
        super.onPause();
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        curPosition = -1;
    }

    public void getRelateNewsList() {
        relateArticledDataCallBack = new RelateArticledDataCallBack();
        componentRelativeInvoker = new ComponentRelativeInvoker(relateArticledDataCallBack);
        if (UserInfo.isLogin(getContext()) && componentItem != null && (componentItem.getType() == RelatedType.HOT_REVIEWS || componentItem.getType() == RelatedType.LASTEST_REVIEW))
            componentRelativeInvoker.getContentComponent(null, componentId, article_id, UserInfo.getUserInfo(getContext()).getUserid(), null, type, page, perPage);
        else if (!TextUtils.isEmpty(tipoff_catalogid)) {
            ArticleListData articleListData = new ArticleListData();
            articleListData.isBaoLiaoDetailComp = true;
            componentRelativeInvoker.getContentComponent(null, componentId, article_id, null, null, tipoff_catalogid, page, perPage, 5, articleListData);
        } else
            componentRelativeInvoker.getContentComponent(null, componentId, article_id, null, null, type, page, perPage);
    }


    @Override
    public void onPlayIcoClick(View rootView, ViewGroup container, View playIcon, ArticleItem item) {
        if (mVideoListPlayerUtil == null) {
            mVideoListPlayerUtil = new VideoListPlayerUtil(getActivity(), mXRListView,this);
            mVideoListPlayerUtil.setHqyNavFragment(RelatedListFragment.this);
        }
        if (item != null && mVideoListPlayerUtil.item != null && mVideoListPlayerUtil.getPlayer() != null
                && mVideoListPlayerUtil.item.equals(item) && mVideoListPlayerUtil.getPlayer().isPlaying()) {
            return;
        }
        mVideoListPlayerUtil.setPlayerContainer(rootView, container, playIcon, !TextUtils.isEmpty(item.getGoodsID()), v -> {
            item.setParentId(cat.getId());
            NewsItemClickUtils.OpenItemNewsHandle(getActivity(), item.getType(), item, cat);
        }, item);
        mVideoListPlayerUtil.setVideoDetail(cat.getId() + "", item);
    }

    @Override
    public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
        page++;
        getRelateNewsList();
    }

    @Override
    public void onRefresh(@NonNull RefreshLayout refreshLayout) {
        page = 1;
        getRelateNewsList();
    }

    class RelateArticledDataCallBack implements DataInvokeCallBack<ArticleListData> {


        @Override
        public void success(ArticleListData data) {
            if (getActivity() == null || getActivity().isFinishing() || getActivity().isDestroyed() ||
                    isDetached() || isRemoving()) {
                return;
            }
            fresh.finishRefresh();
            fresh.finishLoadMore();
            if(!data.more) {
                fresh.finishLoadMoreWithNoMoreData();
            }else{
                fresh.setEnableLoadMore(true);
            }

            if (page==1){

                curPosition = -1;
            }
            mLoadingView.setVisibility(View.GONE);
            if (data.state) {
                if (articlesAdapter!=null&&articlesAdapter.getListContentData()!=null) {
                    if (page == 1) {
                        articlesAdapter.getListContentData().clear();
                    }
                    articlesAdapter.getListContentData().addAll(data.articleList);
                    articlesAdapter.notifyDataSetChanged();

                    if (articlesAdapter.getListContentData().size() == 0) {
                        mEmptyContent.setVisibility(View.VISIBLE);
                    }
                    if(page==1){
                        //触发一下 onScrollStateChanged 否则 视频不会自动播放
                        mXRListView.postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                //mXRListView.smoothScrollBy(2,1);
                                onScrollStateChangedX();
                            }
                        },300);

                    }

                    txExposureEvnet.refreshDatas((int) data.total,new Gson().toJson(articlesAdapter.getListContentData()),null,null,"",getUserVisibleHint());

                }
            }
        }

        @Override
        public void fault(Object data) {
            if (getActivity() == null || getActivity().isFinishing() || getActivity().isDestroyed() ||
                    isDetached() || isRemoving()) {
                return;
            }
            fresh.finishLoadMore();
            fresh.finishRefresh();
            mLoadingView.setVisibility(View.GONE);
        }
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        position = position - mXRListView.getHeaderViewsCount();
        if (position <= 0 && articlesAdapter.getCount() == 0) {
            return;
        }
        ArticleItem article = articlesAdapter.getItem(position);
        TextView titleView = view.findViewById(R.id.newsTitle);
        TextView newsVRTitle = view.findViewById(R.id.newsVRTitle);
        TextView zhiding = view.findViewById(R.id.text_title);//置顶组件
        TextView cmsTitle = view.findViewById(R.id.tv_title_v2);//cms样式
        TextView videoTitle = view.findViewById(R.id.titleTv);//视频导航
        TextView bigImgTitle = view.findViewById(R.id.itemTitle);//大图无分割线
        if (titleView != null) titleView.setTextColor(Color.parseColor("#666666"));
        if (newsVRTitle != null) newsVRTitle.setTextColor(Color.parseColor("#666666"));
        if (zhiding != null) zhiding.setTextColor(Color.parseColor("#666666"));
        if (cmsTitle != null) cmsTitle.setTextColor(Color.parseColor("#666666"));
        if (videoTitle != null) videoTitle.setTextColor(Color.parseColor("#666666"));
        if (bigImgTitle != null) bigImgTitle.setTextColor(Color.parseColor("#666666"));
        article.setPositionInList(position);
            TXReportManager.getInstance().app_jhapp_explore_service_interact("点击查看", article,article.getPositionInList(),articlesAdapter.catalogItem.getName());
        NewsItemClickUtils.OpenItemNewsHandle(getContext(), article.getType(), article, articlesAdapter.catalogItem);
    }

    @Override
    public void onDestroyView() {
        if (mVideoListPlayerUtil != null) {
            mVideoListPlayerUtil.onDestroy();
            mVideoListPlayerUtil = null;
        }
        if (articlesAdapter != null) {
            articlesAdapter.destroy();
            articlesAdapter.listView = null;
        }
        super.onDestroyView();
    }
}